package classloader;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

public class NoParentClassLoader extends ClassLoader {

	
	private ClassLoader parent = getSystemClassLoader();

	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		Class<?> c = findLoadedClass(name);
		if (c == null) {
			try {
				c = findClass(name);
			}catch (SecurityException e) {
				//no-op
			}
		}
		if(c == null) {
			if (parent  != null) {
                c = parent.loadClass(name);
            }
		}
		if(c == null) {
			throw new ClassNotFoundException(name);
		}
		return c;
	}
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		System.out.println(name);
		Class<?> result = null;
		File file = new File(System.getProperty("user.dir") + File.separator + name.replace(".",File.separator) + ".class");
		try {
			byte[] cLassBytes = Files.readAllBytes(Paths.get(file.toURI()));
			result = defineClass(name, cLassBytes, 0, cLassBytes.length);
		}catch(Exception e) {
			//no-op
		}
        return result;
    }
}